package com.ithinksflow.auth.shiro.config;

import com.ithinksflow.auth.shiro.entity.Permission;
import com.ithinksflow.auth.shiro.entity.Role;
import com.ithinksflow.auth.shiro.entity.User;
import com.ithinksflow.auth.shiro.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description
 * @ClassName MyShiroRealm
 * @Author MR.LI
 * @date 2020.11.28 11:02
 */
public class MyShiroRealm  extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;
    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        String name = authenticationToken.getPrincipal().toString();
        User user = loginService.findByName(name);

        if(user == null)
        {
            return null;
        }else{
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    name,user.getPassword().toString(),getName());
            return simpleAuthenticationInfo;
        }
    }
    /**
     *  用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        //查询用户名称
        User user= loginService.findByName(name);
        SimpleAuthorizationInfo  simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        for(Role role : user.getRoles())
        {
            simpleAuthorizationInfo.addRole(role.getRoleName());

            for(Permission permission : role.getPermissions()){
                simpleAuthorizationInfo.addStringPermission(permission.getPermission());

            }
        }
        return simpleAuthorizationInfo;
    }


}
